package fr.vahren.sriksal.dao.impl;

import java.sql.ResultSet;
import java.sql.SQLException;

import org.springframework.dao.support.DataAccessUtils;
import org.springframework.jdbc.core.RowMapper;
import org.springframework.jdbc.core.support.JdbcDaoSupport;

import fr.vahren.sriksal.dao.ITaskProgressDao;

public class TaskProgressDao extends JdbcDaoSupport implements ITaskProgressDao {

	public static final int NO_STEP_COMPLETED = 0;
	private static final String INSERT_TASK = "INSERT INTO SRIKSAL.PROGRESS (NAME,STEP) VALUES (?,?)";
	private static final String UPDATE_STEP = "UPDATE SRIKSAL.PROGRESS SET STEP=? WHERE NAME=?";
	private static final String SELECT_STEP = "SELECT STEP FROM SRIKSAL.PROGRESS WHERE NAME=?";

	/* (non-Javadoc)
	 * @see fr.vahren.sriksal.dao.impl.ITaskProgressDao#createTaskProgress(java.lang.String)
	 */
	@Override
	public void createTaskProgress(String taskName) {
		getJdbcTemplate().update(
				INSERT_TASK,
				taskName, NO_STEP_COMPLETED);
	}

	/* (non-Javadoc)
	 * @see fr.vahren.sriksal.dao.impl.ITaskProgressDao#updateProgress(java.lang.String, int)
	 */
	@Override
	public void updateProgress(String taskName, int step) {
		getJdbcTemplate().update(UPDATE_STEP, step, taskName);
	}

	/* (non-Javadoc)
	 * @see fr.vahren.sriksal.dao.impl.ITaskProgressDao#getProgress(java.lang.String)
	 */
	@Override
	public int getProgress(String taskName) {
		Object[] params = { taskName };
		return DataAccessUtils.intResult(getJdbcTemplate().query(SELECT_STEP,
				params, new RowMapper<Integer>() {

					@Override
					public Integer mapRow(ResultSet rs, int arg1)
							throws SQLException {
						return rs.getInt("STEP");
					}
				}));
	}
}
